import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/log_utils.dart';

import '../../../../resources/str_res_keys.dart';
import '../../../../routers/router_path.dart';
import '../../../../services/device/device_sevices.dart';
import '../../../../utils/brn_row1_delegate.dart';
import '../access_device/model/device_type_detail_model.dart';
import '../access_device/model/device_type_model.dart';
import '../access_device/views/infoHeaderView.dart';
import 'access_device_two_model.dart';
import 'access_device_two_view.dart';
import 'model/three_part_model.dart';

class AccessDeviceTwoController extends GetxController {
  AccessProgressType type = AccessProgressType.paramSet;
  final DeviceServices services = Get.put(DeviceServices());
  List<ThreePartModel> threeList = [];
  ThreePartModel threePartModel = ThreePartModel();
  // String emsName = '';//EMS用户名
  // String emsPwd = '';//EMS用户密码
  // String electricityChangeRate = '';//电流变比
  // String voltageChangeRate = '';//电压率变比
  // String electricChangeRate = '';//电能变比
  // String powerChangeRate = '';//功率变比
  DeviceType deviceType = DeviceType.emsSn;
  bool btnCanClick = false;
  String relationDevice = ''; //关联设备名字
  dynamic arguments;
  late int siteId = 1;
  // 当前选择的设备，（还未通过请求加进去）
  List curSelectDevice = [];
  List<dynamic> associateIds = [];
  // String emsSn = '';//emsSn号
  List<String> titleList = [
    ResKey.siteDeviceAccessEMSName.tr,
    ResKey.siteDeviceAccessEMSPwd.tr,
    ResKey.siteDeviceAccessElectricity.tr,
    ResKey.siteDeviceAccessVoltage.tr,
    ResKey.siteDeviceAccessEnergy.tr,
    ResKey.siteDeviceAccessPower.tr,
    ResKey.deviceAssociatedDevice.tr,
  ];

  final TextEditingController emsNameController =
      TextEditingController(); //EMS用户名
  final TextEditingController emsPwdController =
      TextEditingController(); //EMS用户密码
  final TextEditingController electricityController =
      TextEditingController(); //电流变比
  final TextEditingController voltageController =
      TextEditingController(); //电压率变比
  final TextEditingController energyController = TextEditingController(); //电能变比
  final TextEditingController powerController = TextEditingController(); //功率变比
  final TextEditingController relateController = TextEditingController(); //关联设备
  final TextEditingController threeSiteController =
      TextEditingController(); //第三方站点
  var controllerList = [];
  @override
  void onInit() {
    super.onInit();
    controllerList = [
      emsNameController,
      emsPwdController,
      electricityController,
      voltageController,
      energyController,
      powerController,
      relateController
    ];
    arguments = Get.arguments;

    if (arguments != null) {
      siteId = Get.arguments['siteId'];
      Log.d('paramConfigType==' + arguments['paramConfigType'].toString());

      ///paramConfigType 我们只需要关心1,2,4,6  1储能 2电表,4是逆变器 6是emsSn
      if (arguments['paramConfigType'] != null) {
        if (arguments['paramConfigType'] == 1) {
          deviceType = DeviceType.energy;
        } else if (arguments['paramConfigType'] == 2) {
          deviceType = DeviceType.electric;
        } else if (arguments['paramConfigType'] == 4) {
          deviceType = DeviceType.inverter;
        } else if (arguments['paramConfigType'] == 6) {
          deviceType = DeviceType.emsSn;
        }
      }
    }
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  ///检查电表页面是否可以提交
  checkElectricCommitStatus() {
    if (emsNameController.text.isNotEmpty &&
        emsPwdController.text.isNotEmpty &&
        electricityController.text.isNotEmpty &&
        voltageController.text.isNotEmpty &&
        powerController.text.isNotEmpty &&
        voltageController.text.isNotEmpty &&
        associateIds.isNotEmpty) {
      btnCanClick = true;
    } else {
      btnCanClick = false;
    }
    Log.d('btnCanClick===' + btnCanClick.toString());
    update();
  }

  checkEmsSnCommitStatus() {
    btnCanClick = emsNameController.text.isNotEmpty;
    update();
  }

  ///选择第三方站点
  chooseSite() async {
    DeviceTypeDetailModel typeModel = arguments['productModel'];
    var productId = typeModel.id;
    var param = {'current': 1, 'pageSize': 10000, 'productId': productId};
    var result = await services.getThreePartSite(param);
    if (result != null && result['list'] != null) {
      List resultList = result['list'];
      threeList.clear();
      for (var item in resultList) {
        threeList.add(ThreePartModel.fromJson(item));
      }
    }
    List<String> list = threeList.map((e) => e.siteName ?? '').toList();
    showBottomPop(0, list);
    Log.d('result==' + result.toString());
  }

  ///下一步
  gotoNext() {
    Log.d('gotoNext');
    Map<String, dynamic> map = arguments;
    if (deviceType == DeviceType.electric) {
      var config = {
        'userName': emsNameController.text ?? '',
        'password': emsPwdController.text ?? '',
        'currentRatio': electricityController.text ?? '',
        'voltageRatio': voltageController.text ?? '',
        'energyRatio': energyController.text ?? '',
        'powerRatio': powerController.text ?? '',
      };

      map['config'] = jsonEncode(config);
    } else if (deviceType == DeviceType.energy) {
      var config = {
        'userName': emsNameController.text ?? '',
        'password': emsPwdController.text ?? '',
      };
      map['config'] = jsonEncode(config);
    } else if (deviceType == DeviceType.emsSn) {
      var config = {
        'emsSn': emsNameController.text ?? '',
      };
      map['config'] = jsonEncode(config);
    } else {
      var config = {
        'thirdSiteId': threePartModel.id,
      };
      map['config'] = jsonEncode(config);
    }

    if (associateIds.isNotEmpty) {
      map['associateId'] = associateIds;

      Log.d('associateIds=====' + associateIds.toString());
    }
    if (threePartModel.id != null) {
      map['thirdSiteId'] = threePartModel.id;
    }

    Get.toNamed(RouterPath.siteDeviceAccessThree, arguments: arguments);
  }

  ///选择关联设备
  chooseRelatedDevice() {
    Get.toNamed(RouterPath.subDeviceTree,
            arguments: {'siteId': siteId, 'selectDeviceIds': curSelectDevice})
        ?.then((value) {
      Log.d('value===' + value.toString());
      if (value is List<Map>) {
        curSelectDevice = value;
        if (curSelectDevice.isNotEmpty) {
          String string = jsonEncode(curSelectDevice);
          Log.d('string===' + string.toString());
          var tempString = string.replaceAll('deviceName', 'name');
          curSelectDevice = jsonDecode(tempString);
          Log.d('curSelectDevice===' + curSelectDevice.toString());

          if (curSelectDevice.length == 1) {
            relationDevice = curSelectDevice[0]['name'].toString();
          } else {
            relationDevice = '${curSelectDevice[0]['name']}...';
          }
          relateController.text = relationDevice;
        }
        associateIds = curSelectDevice.map((e) => e['id'] ?? 0).toList();
        checkElectricCommitStatus();
        update();
        Log.d('associateIds==' + associateIds.toString());
      }
    });
  }

  ///弹出底部弹窗
  showBottomPop(int index, List<String> list) {
    BrnMultiDataPicker(
      context: Get.context!,
      title: ResKey.selectSite.tr,
      confirmClick: (indexList) {
        threePartModel = threeList[indexList[0]];
        threeSiteController.text = threePartModel.siteName!;
        if (deviceType == DeviceType.inverter) {
          //逆变器
          btnCanClick = true;
        }
        update();
      },
      delegate: Brn1RowDelegate(list),
    ).show();
  }
}
